﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Lists;
using System.Data.SqlClient;

namespace ReportGenerators
{
    public partial class FrmThamSoBaoCaoTongHopHangKyGui : BasicForms.FrmThamSoBaoCao
    {
        public FrmThamSoBaoCaoTongHopHangKyGui()
        {
            InitializeComponent();
        }

        private void FrmThamSoBaoCaoTongHopHangKyGui_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;

            #region cmbNhaCungCap
            DataView dvDoiTuongNghiepVu = DanhMucDoiTuongNghiepVu.GetAll().DataView;
            cmbDoiTuongNghiepVu.DataSource = dvDoiTuongNghiepVu;
            cmbDoiTuongNghiepVu.DisplayColumn = "Ten";
            cmbDoiTuongNghiepVu.ValueColumn = "ID";
            cmbDoiTuongNghiepVu.AddVisibleColumn("Ma", "Mã");
            cmbDoiTuongNghiepVu.AddVisibleColumn("Ten", "Tên");
            cmbDoiTuongNghiepVu.Buttons[1].Visible = false;
            #endregion

            #region cmbVatTuHangHoa
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT ID FROM NhomVatTuHangHoa WHERE Ma='KYGUI'", con);
            SqlDataReader dr = cmd.ExecuteReader();
            string nhomVatTuHangHoaID = "";
            string filterExpression = "";
            while (dr.Read())
            {
                nhomVatTuHangHoaID = dr[0].ToString();
                filterExpression = "NhomVatTuHangHoaID = '" + nhomVatTuHangHoaID + "'";
            }
            dr.Close();
            DataView dvVatTuHangHoa = DanhMucVatTuHangHoa.Filter(filterExpression).DataView;
            //DataView dvVatTuHangHoa = DanhMucVatTuHangHoa.Filter("NhomVatTuHangHoaID='E9D29D9C-17C5-4F5B-A488-9A07F51DEFBF'").DataView;
            cmbVatTuHangHoa.DataSource = dvVatTuHangHoa;
            cmbVatTuHangHoa.DisplayColumn = "Ten";
            cmbVatTuHangHoa.ValueColumn = "ID";
            cmbVatTuHangHoa.AddVisibleColumn("Ma", "Mã");
            cmbVatTuHangHoa.AddVisibleColumn("Ten", "Tên");
            cmbVatTuHangHoa.Buttons[1].Visible = false;
            #endregion
        }

        private void cmbDoiTuongNghiepVu_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                cmbDoiTuongNghiepVu.EditValue = Guid.Empty;
        }
        protected override void PrepareDataForReport()
        {
            DoiTuongNghiepVu selectedDoiTuongNghiepVu = null;
            if (cmbDoiTuongNghiepVu.EditValue is Guid || cmbDoiTuongNghiepVu.Text != "")
            {
                selectedDoiTuongNghiepVu = DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuongNghiepVu.EditValue);
            }
            else
            {
                MessageBox.Show("Phải chọn đối tượng nghiệp vụ");
                cmbDoiTuongNghiepVu.Focus();
                return;
            }

            VatTuHangHoa selectedVatTuHangHoa = null;
            if (cmbVatTuHangHoa.EditValue is Guid || cmbVatTuHangHoa.Text != "")
            {
                selectedVatTuHangHoa = DanhMucVatTuHangHoa.Instance.GetByID((Guid)cmbVatTuHangHoa.EditValue);
            }

            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            ReportTemplates.QuanLyKho.BaoCaoTongHopHangKyGui.DsBaoCaoTongHopHangKyGui ds = new ReportTemplates.QuanLyKho.BaoCaoTongHopHangKyGui.DsBaoCaoTongHopHangKyGui();
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;
                SqlDataAdapter da = null;

                cmd.CommandText = "Select_ThongTinDoanhNghiep2";
                cmd.Parameters.Clear();
                da = new SqlDataAdapter(cmd);
                da.Fill(ds.ThongTinDoanhNghiep);

                DataTable dtChiTietTongHopNhapXuatTon = ds.ChiTietBaoCaoTongHopHangKyGui;
                dtChiTietTongHopNhapXuatTon.Rows.Add(dtChiTietTongHopNhapXuatTon.NewRow());
                dtChiTietTongHopNhapXuatTon.Rows[0]["KyBaoCao"] = _KyBaoCao.Ten;
                dtChiTietTongHopNhapXuatTon.Rows[0]["TenNhaCungCap"] = selectedDoiTuongNghiepVu.Ten;

                ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemKhoaSoGanNhat(_KyBaoCao.ThoiDiemDau);
                if (thoiDiemKhoaSoGanNhat == null) throw new GeneralLibs.CustomException("Không có thời điểm khóa sổ trước " + _KyBaoCao.ThoiDiemDau.ToString());

                cmd = new SqlCommand("SELECT ID FROM NhomVatTuHangHoa WHERE Ma='KYGUI'", con);
                SqlDataReader dr = cmd.ExecuteReader();
                string nhomVatTuHangHoaID = "";
                string filterExpression = "";
                while (dr.Read())
                {
                    nhomVatTuHangHoaID = dr[0].ToString();
                    filterExpression = "NhomVatTuHangHoaID = '" + nhomVatTuHangHoaID + "'";
                }
                dr.Close();

                if (nhomVatTuHangHoaID != "")
                {
                    BasicForms.FrmProgressBarDev.StartShowProgress();

                    DataTable dtKhoanMucBaoCaoTongHopHangKyGui = ds.KhoanMucBaoCaoTongHopHangKyGui;
                    if (selectedVatTuHangHoa == null)
                    {
                        int i = 0;
                        foreach (VatTuHangHoa vatTuHangHoa in DanhMucVatTuHangHoa.Filter(filterExpression))
                        {
                            i++;
                            DataRow khoanMucRow = dtKhoanMucBaoCaoTongHopHangKyGui.NewRow();
                            khoanMucRow["MaVatTuHangHoa"] = vatTuHangHoa.Ma;
                            khoanMucRow["TenVatTuHangHoa"] = vatTuHangHoa.Ten;
                            khoanMucRow["DonViTinh"] = vatTuHangHoa.DonViTinh;
                            khoanMucRow["GiaBia"] = vatTuHangHoa.GiaBia;


                            TonKho phatSinhNhap = TonKho.CalculatePhatSinhNhapTheoNhaCungCap(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoa.ID);
                            khoanMucRow["SoLuongNhap"] = phatSinhNhap.SoLuong;
                            khoanMucRow["GiaTriNhap"] = phatSinhNhap.SoLuong * vatTuHangHoa.GiaBia;

                            TonKho phatSinhXuatBan = TonKho.CalculatePhatSinhXuatBanMatHang(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, vatTuHangHoa.ID);
                            khoanMucRow["SoLuongXuat"] = phatSinhXuatBan.SoLuong;
                            khoanMucRow["GiaTriXuat"] = phatSinhXuatBan.SoLuong * vatTuHangHoa.GiaBia;

                            TonKho phatSinhXuatTra = TonKho.CalculatePhatSinhXuatTraMatHang(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, vatTuHangHoa.ID, selectedDoiTuongNghiepVu.ID);
                            khoanMucRow["SoLuongXuatTra"] = phatSinhXuatTra.SoLuong;
                            khoanMucRow["GiaTriXuatTra"] = phatSinhXuatTra.SoLuong * vatTuHangHoa.GiaBia;

                            TonKho tonCuoiKy = TonKho.CalculateTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVaoTheoKho(cmd, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoa.ID);
                            khoanMucRow["SoLuongCuoiKy"] = phatSinhNhap.SoLuong - phatSinhXuatBan.SoLuong - phatSinhXuatTra.SoLuong;
                            khoanMucRow["GiaTriCuoiKy"] = (decimal)khoanMucRow["SoLuongCuoiKy"] * vatTuHangHoa.GiaBia;

                            if (!chkChiHienThiHangTon.Checked || phatSinhXuatBan.SoLuong > 0 || phatSinhNhap.SoLuong > 0 || phatSinhXuatTra.SoLuong > 0)
                                dtKhoanMucBaoCaoTongHopHangKyGui.Rows.Add(khoanMucRow);

                            BasicForms.FrmProgressBarDev.Status = string.Format("Đã xử lý {0}/{1} thuốc", ++i, DanhMucVatTuHangHoa.Instance.Count);
                        }
                    }
                    else
                    {
                        VatTuHangHoa vatTuHangHoa = selectedVatTuHangHoa;

                        DataRow khoanMucRow = dtKhoanMucBaoCaoTongHopHangKyGui.NewRow();
                        khoanMucRow["MaVatTuHangHoa"] = vatTuHangHoa.Ma;
                        khoanMucRow["TenVatTuHangHoa"] = vatTuHangHoa.Ten;
                        khoanMucRow["DonViTinh"] = vatTuHangHoa.DonViTinh;
                        khoanMucRow["GiaBia"] = vatTuHangHoa.GiaBia;


                        TonKho phatSinhNhap = TonKho.CalculatePhatSinhNhapTheoNhaCungCap(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoa.ID);
                        khoanMucRow["SoLuongNhap"] = phatSinhNhap.SoLuong;
                        khoanMucRow["GiaTriNhap"] = phatSinhNhap.SoLuong * vatTuHangHoa.GiaBia;

                        TonKho phatSinhXuatBan = TonKho.CalculatePhatSinhXuatBanMatHang(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, vatTuHangHoa.ID);
                        khoanMucRow["SoLuongXuat"] = phatSinhXuatBan.SoLuong;
                        khoanMucRow["GiaTriXuat"] = phatSinhXuatBan.SoLuong * vatTuHangHoa.GiaBia;

                        TonKho phatSinhXuatTra = TonKho.CalculatePhatSinhXuatTraMatHang(cmd, _KyBaoCao.ThoiDiemDau, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoa.ID);
                        khoanMucRow["SoLuongXuatTra"] = phatSinhXuatTra.SoLuong;
                        khoanMucRow["GiaTriXuatTra"] = phatSinhXuatTra.SoLuong * vatTuHangHoa.GiaBia;

                        TonKho tonCuoiKy = TonKho.CalculateTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVaoTheoKho(cmd, _KyBaoCao.ThoiDiemCuoi, selectedDoiTuongNghiepVu.ID, vatTuHangHoa.ID);
                        khoanMucRow["SoLuongCuoiKy"] = phatSinhNhap.SoLuong - phatSinhXuatBan.SoLuong - phatSinhXuatTra.SoLuong;
                        khoanMucRow["GiaTriCuoiKy"] = (decimal)khoanMucRow["SoLuongCuoiKy"] * vatTuHangHoa.GiaBia;

                        if (!chkChiHienThiHangTon.Checked || phatSinhXuatBan.SoLuong > 0 || phatSinhNhap.SoLuong > 0 || phatSinhXuatTra.SoLuong > 0)
                            dtKhoanMucBaoCaoTongHopHangKyGui.Rows.Add(khoanMucRow);
                    }

                    _Report = new ReportTemplates.Khac.BaoCaoTongHopHangKyGui.RptBaoCaoTongHopHangKyGui();
                    _Report.SetDataSource(ds);
                }
                else
                {
                    MessageBox.Show("Không có nhóm thuốc ký gửi trong danh mục.");
                }
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
            }

            BasicForms.FrmProgressBarDev.FinishShowProgress();
        }
        protected override void PrintReport()
        {
            if (_Report != null)
            {
                ReportTemplates.FrmPrintReport frm = new ReportTemplates.FrmPrintReport(_Report, "Tổng hợp tồn theo nhà cung cấp");
                frm.Show();
            }
        }
    }
}
